define([], function () {
    return ['$scope', '$filter', '$stateParams', 'config', 'MMWService', '$rootScope',
        function ($scope, $filter, $stateParams, config, $MMWService, $rootScope) {
            // 20220926 modify by chenshibo for#118836：增加分页
            $scope.PageConfig = { page: 0, page_count: 50 };
            $scope.pcs_filter = {};
            // 20230912 modify by shiwl for#0145788: [ORACLE][6.0][在线][工位机测试]序号生成-序号预显页面的分页问题
            $scope.dispatch_filter = {};
            $scope.init = function () {
                $scope.condition = {
                    plot_no: '',
                    serial_number_start: '',
                    serial_number_end: '',
                    factory: 1
                };
                $scope.pcs_detail = [];
            };

            $scope.back = function () {
                $scope.$root.changeProgram('home', true);
            };

            $scope.loadPlotList = function () {
                $MMWService.showQueryListPNIG({
                    page_mode: 29,
                    pageRecord: 50,
                    condition: [
                        { name: $filter('translate')('common.queryList.plot_no'), column_name: 'lotno', query_mode: '2', value: $scope.condition.plot_no, merge_condition_model: 'AND' }
                    ],
                    header: [
                        { label: $filter('translate')('common.queryList.plot_no'), code: 'page_no' },
                        { label: $filter('translate')('common.queryList.wo_c'), code: 'wono' },
                        { label: $filter('translate')('common.queryList.item_c'), code: 'productno' },
                        { label: $filter('translate')('common.queryList.item_n'), code: 'productname' },
                        { label: $filter('translate')('common.queryList.item_spec'), code: 'itemspec' }
                    ],
                    setCondition: function (conditions) {
                        conditions.push({ column_name: 'status', query_mode: $scope.condition.factory, value: '11', merge_condition_model: 'AND' });
                        return conditions;
                    },
                    selectCode: $scope.condition.plot_no,
                    confirm: function (selectItem) {
                        $scope.condition.plot_no = selectItem.page_no;
                    }
                });
            };

            $scope.search = function () {
                var msg = checkCondtions();
                if (msg === '') {
                    serial_number_generation_info_get($scope.condition);
                } else {
                    $scope.$root.showAlert(msg);
                }
            };

            $scope.serialPreview = function () {
                var msg = '';
                if ($scope.condition.plot_no == '') {
                    msg += $filter('translate')('E03.msg.plot_no_empty');
                }

                if (msg === '') {
                    serial_number_pre_display_get($scope.condition);
                } else {
                    $scope.$root.showAlert(msg);
                }
            };

            $scope.selectAll = function () {
                $scope.$root.showLoading();
                $scope.isSelectAll = !$scope.isSelectAll;
                if ($scope.pcs_detail && $scope.pcs_detail.length > 0) {
                    $scope.pcs_detail.forEach(function (pcs) {
                        pcs.isSelect = $scope.isSelectAll + '';
                    });
                }
                $scope.$root.hideLoading();
            };

            $scope.itemClick = function (item) {
                item.isSelect = (item.isSelect == 'true' ? 'false' : 'true');
                if (item.isSelect == 'false') {
                    $scope.isSelectAll = false;
                }
            };

            $scope.confirm = function () {
                serial_number_process_json($scope.condition.plot_no, function (data) {
                    //data
                    $scope.$root.showToast($filter('translate')('E03.msg.success'));
                    $scope.search();
                    // printTag(data.pcs_detail, 0);
                });
            };
            //分頁
            $scope.getPages = function (list, PageConfig, filterItem) {
                if (list) {
                    var temp_list = list.filter(function (item, index, array) {
                        var isOK = true,
                            keys = Object.keys(filterItem);
                        for (var i = 0; i < keys.length; i++) {
                            var key = keys[i];
                            if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                    isOK = false;
                                    break;
                                }
                            }
                        }
                        return isOK;
                    });
                    if (PageConfig) {
                        if (temp_list.length != 0) {
                            PageConfig.total_page = Math.ceil(temp_list.length / PageConfig.page_count);

                            if (PageConfig.page >= PageConfig.total_page) {
                                PageConfig.page = 0;
                            }
                            var index = PageConfig.page * PageConfig.page_count;
                            return temp_list.slice(index, index + PageConfig.page_count);
                        } else {
                            PageConfig.total_page = 1;
                            PageConfig.page = 0;
                        }
                    } else {
                        return temp_list;
                    }
                } else {

                    return list;
                }
            };


            function checkCondtions() {
                var msg = '';
                if ($scope.condition.plot_no == '') {
                    msg += $filter('translate')('E03.msg.plot_no_empty');
                } else if (($scope.condition.serial_number_start + $scope.condition.serial_number_end) != '') {
                    if ($scope.condition.serial_number_start == '' || $scope.condition.serial_number_end.length == '') {
                        msg += $filter('translate')('E03.msg.serial_no_not_enough');    //起始序號未填寫完整
                    } else if (isNaN($scope.condition.serial_number_start) || isNaN($scope.condition.serial_number_end)) {
                        msg += $filter('translate')('E03.msg.serial_no_illegal');   //成品序號格式錯誤
                    } else if (+$scope.condition.serial_number_start > +$scope.condition.serial_number_end) {
                        msg += $filter('translate')('E03.msg.serial_no_start_less_than_end'); //起始序號不可大於結束序號
                    }
                }
                return msg;
            }

            function serial_number_generation_info_get(condition) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SN.serial_number_generation_info_get',
                    content: {
                        plot_no: condition.plot_no,
                        serial_number_start: condition.serial_number_start,
                        serial_number_end: condition.serial_number_end
                    },
                    success: function (data) {
                        $scope.generated = data.generated;
                        $scope.pcs_detail = data.pcs_detail;
                        create_max_detail = [];
                    }
                });
            }
            var create_max_detail = [];
            function serial_number_pre_display_get(condition) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SN.serial_number_pre_display_get',
                    content: {
                        plot_no: condition.plot_no,
                        serial_number_start: condition.serial_number_start,
                        serial_number_end: condition.serial_number_end
                    },
                    success: function (data) {
                        $scope.pcs_detail = data.pcs_detail;
                        create_max_detail = data.create_max_detail;
                    }
                });
            }

            function serial_number_process_json(plot_no, callback) {
                var pcs_detail_list = [];
                // 20231114 modify by wenwei for M#129293 print_label_num、isSelect 序號生成頁面不顯示，且生成不需要此參數，故保留參數但傳值為空
                $scope.pcs_detail.forEach(function (item) {
                    item.print_label_num = null
                    item.isSelect = null
                    pcs_detail_list.push(item);
                });

                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SN.serial_number_process',
                    content: {
                        ip: config.server.ip,
                        port: config.server.port,
                        plot_no: plot_no,
                        pcs_detail: pcs_detail_list,
                        create_max_detail: create_max_detail,
                        // 20230419 add by 文蔚 for M# 0119702: [標準][DEV]序號管理-序列号打印-手動生成，生成與打印方開 
                        isGenerate:true
                    },
                    success: function (data) {
                        //$scope.pcs_detail = data.pcs_detail;
                        if (callback)
                            callback(data);
                    }
                });
            }

            function printTag(tags, index) {
                if (tags && index < tags.length) {
                    if (window.nodeRequire) {
                        var exec = window.nodeRequire('child_process').exec;
                        $rootScope.showToast($filter('translate')('E03.msg.prpare_print', { index: index }));
                        exec(tags[index].commandline, function (error, stdout, stderr) {
                            if (error) {
                                $rootScope.showAlert($filter('translate')('E01.msg.cantprint'));
                            }
                            index = index + 1;
                            printTag(tags, index);
                        });
                    }
                }
            }
        }];
});
